'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async commentcreat() {
    const { ctx } = this;
    const { uid, releaseid, tutorialid, commenttext, appointmentid, fieldid } = ctx.request.body;
    if (!(releaseid || tutorialid || appointmentid || fieldid)) {
      return ctx.body = { success: false, msg: '请传入必要的参数' };
    }
    const create = {};
    create.commentTime = Date.now();
    create.commenttext = commenttext;
    create.uid = uid;
    if (releaseid) {
      create.releaseid = releaseid;
    }
    if (tutorialid) {
      create.tutorialid = tutorialid;
    }
    if (appointmentid) {
      create.appointmentid = appointmentid;
    }
    if (fieldid) {
      create.fieldid = fieldid;
    }
    try {
      await ctx.model.Comment.create(
        create
      );
      ctx.body = { success: true, msg: '评论成功' };
    } catch (e) {
      ctx.body = { success: false, msg: '评论失败' };
    }
  }

  async commentfind() {
    const { ctx } = this;
    const { uid, releaseid, tutorialid, appointmentid, fieldid, page } = ctx.request.body;
    const limit = 10;
    const offset = (page - 1) * limit || 0;
    const where = {};
    if (uid) {
      where.uid = uid;
    }
    if (releaseid) {
      where.releaseid = releaseid;
    }
    if (tutorialid) {
      where.tutorialid = tutorialid;
    }
    if (appointmentid) {
      where.appointmentid = appointmentid;
    }
    if (fieldid) {
      where.fieldid = fieldid;
    }
    try {
      await ctx.model.Comment.hasOne(ctx.model.User, {
        foreignKey: 'uid',
        sourceKey: 'uid',
      });
      const res = await ctx.model.Comment.findAndCountAll({
        where,
        limit,
        offset,
        include: [{
          model: ctx.model.User,
          attributes: {
            exclude: [ 'pas' ],
          },
        }],
      }
      );
      ctx.body = { success: true, data: res };
    } catch (e) {
      ctx.body = { success: false, msg: '查询失败' };

    }
  }

  async commentdelete() {
    const { ctx } = this;
    const { commentid } = ctx.request.body;
    if (!commentid) {
      return ctx.body = { success: false, msg: '请传入评论id' };
    }
    try {
      await ctx.model.Comment.destroy({
        where: {
          commentid,
        },
      });
      ctx.body = { success: true, msg: '删除成功' };
    } catch (e) {
      ctx.body = { success: false, msg: '删除失败' };
    }
  }
}

module.exports = HomeController;
